package com.cares.core.mng.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cares.core.base.service.BaseService;
import com.cares.core.mng.repository.RoleMybatisDao;
import com.cares.entity.base.PageModel;
import com.cares.entity.mng.Orgnization;
import com.cares.entity.mng.Role;

import com.google.common.collect.Maps;

/**
 * 
 * @author
 */
@Service("roleService")
@Transactional(readOnly = true)
public class RoleService extends BaseService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	private static Logger logger = LoggerFactory.getLogger(RoleService.class);

	@Autowired
	private RoleMybatisDao roleDao;
	
	@Autowired
	@Qualifier("orgService")
	private OrgService orgService;

	/**
	 * 先访问Memcached, 使用JSON字符串存放对象以节约空间.
	 */
	public Role getRole(Long id) {

		Role role = null;
		role = roleDao.get(id);

		return role;
	}

	public Role findRoleByName(String roleName) {
		List<Role> listRole = searchRole(roleName);
		Role role = null;
		if (null != listRole && listRole.size() > 0)
			role = listRole.get(0);
		return role;
	}

	/**
	 * 根据角色名称查询角色列表
	 * @param roleName
	 * @return
	 */
	public List<Role> searchRole(String roleName) {
		Map<String, Object> parameters = Maps.newHashMap();
		parameters.put("roleName", roleName);
		return roleDao.search(parameters);
	}

	/**
	 * 获取所有角色信息
	 * @return
	 */
	public List<Role> getAllRole() {
		return searchRole(null);
	}

	/**
	 * 修改角色
	 * @param role
	 */
	public void updateRole(Role role) {
		Role dbRole = roleDao.get(role.getId());
		dbRole.setRoleName(role.getRoleName());
		dbRole.setRoleDesp(role.getRoleDesp());
		dbRole.setAvailable(role.getAvailable());
		dbRole.setUpdateUser(getCurrentUserName());
		dbRole.setUpdateTime(dateProvider.getDate());
		
		Orgnization org = orgService.get(role.getOrgId());
		if(org!=null && StringUtils.isNotEmpty(org.getOrgPath())) {
			dbRole.setOrgId(org.getId());
			dbRole.setOrgCode(org.getOrgCode());
			dbRole.setOrgPath(org.getOrgPath());
		} else {
			dbRole.setOrgId(getCurrentUserOrgId());
			dbRole.setOrgCode(super.getCurrentUserOrgCode());
			dbRole.setOrgPath(super.getCurrentUserOrgPath());
		}
		roleDao.update(dbRole);
		
	}

	/**
	 * 新增角色
	 * @param role
	 */
	public void saveRole(Role role) {

		role.setAvailable("Y");
		role.setRoleType("C");
		Orgnization org = orgService.get(role.getOrgId());
		if(org!=null && StringUtils.isNotEmpty(org.getOrgPath())) {
			role.setOrgCode(org.getOrgCode());
			role.setOrgPath(org.getOrgPath());
		} else {
			role.setOrgId(super.getCurrentUserOrgId());
			role.setOrgCode(super.getCurrentUserOrgCode());
			role.setOrgPath(super.getCurrentUserOrgPath());
		}
		role.setCreateUser(getCurrentUserName());
		role.setCreateTime(dateProvider.getDate());
		roleDao.save(role);
	}

	/**
	 * 删除角色
	 * @param id
	 */
	public void deleteRole(Long id) {
		Map map = new HashMap();
		map.put("id", id);
		map.put("roleId", id);
		roleDao.delRoleMenu(map);
		roleDao.deleteUserRolesById(id);
		roleDao.delete(id);

	}

	/**
	 * 新增角色菜单信息
	 * @param roleId
	 * @param ids
	 */
	public void addRoleMenu(Long roleId, List<String> ids) {
		Map map = new HashMap();
		map.put("id", roleId);
		map.put("roleId", roleId);
		roleDao.delRoleMenu(map);
		for (String mid : ids) {
			map.put("mid", mid);
			this.roleDao.addRoleMenu(map);
		}
	}

	/**
	 * 删除角色菜单信息
	 * @param map
	 */
	public void delRoleMenu(Map map) {
		this.roleDao.delRoleMenu(map);
	}

	/**
	 * 更新角色菜单操作信息
	 * @param map
	 */
	public void updateRoleOpt(Map map) {
		this.roleDao.updateRoleOpt(map);
	}

	/**
	 * 角色菜单信息校验
	 * @param map
	 * @return
	 */
	public boolean checkRoleMenu(Map map) {
		int l = this.roleDao.checkRoleMenu(map);
		if (l == 0)
			return true;
		else
			return false;
	}

	/**
	 * 获取角色菜单操作信息
	 * @param map
	 * @return
	 */
	public String getRoleOpts(Map map) {
		return this.roleDao.getRoleOpts(map);
	}

	/**
	 * 获取角色菜单信息
	 * @param id
	 * @return
	 */
	public List<Map> getRoleMenus(Long id) {

		List<Map> menus = this.roleDao.getRoleMenus(id);

		return menus;
	}

	/**
	 * 角色列表信息查询
	 * @param pageModel
	 * @return
	 */
	public String getRoles(PageModel<Role> pageModel) {
		String result = "";
		JSONObject json = new JSONObject();
		List<Map> rows = new ArrayList<Map>();
		
		Role condition = (Role)pageModel.getCondition();
		condition.setOrgPath(getCurrentUserOrgPath());
		
		List<Role> roles = this.roleDao.getAll(pageModel);

		for (Role role : roles) {
			Map<String, Object> row = new HashMap<String, Object>();
			row.put("id", role.getId());
			row.put("roleName", role.getRoleName());
			row.put("roleDesp", role.getRoleDesp());
			row.put("available", role.getAvailable());
			row.put("orgId", role.getOrgId());
			Orgnization org = orgService.get(role.getOrgId());
			if(org!=null) {
				role.setOrgNameCn(org.getNameCn());
			}
			row.put("orgNameCn", role.getOrgNameCn());
			rows.add(row);
		}

		try {
			json.put("total", this.roleDao.count(pageModel));
			json.put("rows", rows);

			result = json.toString();
		} catch (JSONException e) {
		}

		return result;
	}

	/**
	 * 更新角色菜单信息
	 * @param roleId
	 * @param funcId
	 */
	public void updateRoleAuth(Long roleId, List<String> funcId) {

		Map<String, String> funcMap = new HashMap<String, String>();
		Long menuId = null;
		String tempId = StringUtils.EMPTY;
		if (funcId.size() > 0) {// 前台传入的字符串重组：菜单ID-功能点ID;菜单ID-功能点ID;...
			for (int i = 0; i < funcId.size(); i++) {
				tempId = StringUtils.EMPTY;
				int ii = funcId.get(i).indexOf("-");
				if (ii != -1) {
					menuId = new Long(funcId.get(i).substring(0, ii));
					tempId = funcId.get(i).substring(ii + 1,
							funcId.get(i).length());
					if (null != funcMap.get(String.valueOf(menuId))) {
						funcMap.put(String.valueOf(menuId), funcMap.get(String
								.valueOf(menuId))
								+ ";" + tempId);
					} else {
						funcMap.put(String.valueOf(menuId), tempId);
					}
				} else {
					menuId = new Long(funcId.get(i));
					funcMap.put(menuId.toString(), null);
				}

			}
		}

		Map map = new HashMap();
		map.put("roleId", roleId);
		roleDao.delRoleMenu(map);

		Set key = funcMap.keySet();
		Iterator<String> kk = key.iterator();
		while (kk.hasNext()) {// 重新插入
			String ttk = kk.next();
			menuId = new Long(ttk);
			if (menuId.intValue() != 0) {
				map.put("menuId", menuId);
				map.put("roleId", roleId);
				map.put("func", funcMap.get(ttk));
				this.roleDao.addRoleMenu(map);
			}
		}
	}
}
